import threading, traceback
from datetime import datetime
from rich.panel import Panel
from rich.table import Table
from rich.align import Align
from rich.text import Text
from rich.console import Group
from rich import box
from threading import RLock

class CopyrightPanel:

    def __init__(self, title="[ Copyright ]", style="bright_blue"):
        self.title = title
        self.style = style

    def __rich__(self) -> Panel:
        sponsor_message = Table.grid(padding=1)
        sponsor_message.add_column(style="green", justify="right")
        sponsor_message.add_column(justify="left")
        sponsor_message.add_row(
            "Gitee",
            "[u blue link=https://gitee.com/ray0728/blog-scripts]https://gitee.com/ray0728/blog-scripts",
        )
        sponsor_message.add_row(
            "Blog",
            "[u blue link=https://www.ray0728.cn/]https://www.ray0728.cn/",
        )
        sponsor_message.add_row(
            "Email",
            "[u blue link=mailto://51101661@qq.com]51101661@qq.com",
        )
        intro_message = Text.from_markup("""\
Please provide more comments and bugs! or buy me a coffee to say good job.

- Ray

The UI is developed based on the [bold magenta]Rich[/] component.
[u blue link=https://github.com/sponsors/willmcgugan]https://github.com/sponsors/willmcgugan[/]
""")
        message = Table.grid(expand=True)
        message.add_column()
        message.add_column()
        message.add_row(intro_message, sponsor_message)

        message_panel = Panel(
            message,
            title=self.title,
            border_style=self.style,
        )
        return message_panel

class ClockPanel:
    def __init__(self, title, style):
        self.title = title
        self.style = style

    def __rich__(self) -> Panel:
        grid = Table.grid(expand=True)
        grid.add_column(justify="center", ratio=1)
        grid.add_column(justify="right")
        grid.add_row(
            self.title,
            datetime.now().ctime().replace(":", "[blink]:[/]"),
        )
        return Panel(grid, style=self.style)

class LogPanel:

    def __printStack(self):
        for line in traceback.format_stack():
            print(line.strip())

    def __initHeader(self):
        grid = Table.grid(expand=True)
        grid.add_column(justify="center", ratio=1)
        grid.add_column(justify="center", ratio=2)
        grid.add_column(justify="center", ratio=1)
        grid.add_column(justify="center", ratio=10)
        grid.add_row("Time", "Level", "Tag", "Message", style="chartreuse4")
        return grid

    def __init__(self, title="[ Log ]", max=40, style=None):
        self.title = title
        self.style = style
        self.loglist = []
        self.renderlist = None
        self.max = max
        self._lock = threading.RLock()
        self.header = self.__initHeader()

    def recode(self, level, tag, msg):
        # self.__printStack()
        self._lock.acquire()
        self.loglist.append({"time":datetime.now().strftime("%H[blink]:[/]%M[blink]:[/]%S"), "level":level, "tag":tag, "msg":msg})
        if(len(self.loglist) > self.max):
            self.loglist.pop(0)
        self._lock.release()

    def __rich__(self) -> Panel:
        # self.__printStack()
        mesg = None
        self._lock.acquire()
        self.renderlist = self.loglist.copy()
        self._lock.release()
        details = Table.grid(expand=True)
        details.add_column(justify="left", ratio=1)
        details.add_column(justify="center", ratio=2)
        details.add_column(justify="left", ratio=1)
        details.add_column(justify="left", ratio=10)

        for log in self.renderlist:
            style = None
            if(log["level"].upper() == "ERROR"):
                style = "yellow on red1"
            elif(log["level"].upper() == "DEBUG"):
                style = "yellow3"
            elif(log["level"].upper() == "WARN"):
                style = "red3"
            details.add_row(
                log["time"],
                log["level"],
                log["tag"],
                log["msg"],
                style = style
            )
        info = Table.grid(expand=True, padding=1)
        info.add_row(self.header)
        info.add_row(details)
        mesg = "Hello, World!"
        return Panel(info, title=self.title, border_style="grey93", padding=1)
